grub_path=""

function get_grub_path()
{
    local efi_flag=0
    local efi_grub_path=""
    local bios_grub_path="/boot/grub2/grub.cfg"

    if [ $(df | grep -c /boot/efi) -ne 0 ]
    then
        efi_flag=1
    fi

    if [ $(find /sys/firmware/efi/ -maxdepth 1 -type f | wc -l) -ne 0 ]
    then
        efi_flag=1
    fi

    efi_grub_path=$(find /boot/efi/EFI -type f -name grub.cfg)
    if [ ! -f "${efi_grub_path}" ]
    then
        efi_flag=0
    fi

    if [ ${efi_flag} -eq 1 ]
    then
        grub_path=${efi_grub_path}
    else
        grub_path=${bios_grub_path}
    fi
}

get_grub_path
echo "grub_path: ${grub_path}"

function get_menuentry_info()
{
    local menuentry=""
    local menuentry_ctx=""
    local kernel_version=""
    local initrd_file=""
    local entry_nums=""
    local line=""
    local line_count=""
    local saved_entry=""

    if [ -f "/boot/grub2/grubenv" ]
    then
        saved_entry=$(cat /boot/grub2/grubenv | grep saved_entry | awk -F "=" '{ print $2 }')
    fi

    # 先获取所有的 menuentry 所在行号：匹配规则：以 menuentry 开头，以 { 结尾所在的行
    entry_nums=$(cat ${grub_path} | grep -n -E "^(menuentry|\s+menuentry)\s*.+({|{\s+)$" | awk -F ":" '{ print $1 }')
    for line in ${entry_nums}
    do
        # 从 menuentry 所在行号后寻找第一个 } 所在行号
        line_count=$(sed -n "${line},\$p" ${grub_path} | grep -n -E "^(}|\s+}|\s+}\s+)$" | head -n 1 | awk -F ":" '{ print $1 }')
        if [ -z "${line_count}" ]
        then
            continue
        fi

        # menuentry ... { ... } 之间的内容即为需要用到的 menuentry 信息
        line_count=$((line_count-1))
        menuentry_ctx=$(sed -n "${line},+${line_count}p" ${grub_path})
        if [ -z "${menuentry_ctx}" ]
        then
            continue
        fi

        # vmlinuz 和 initrd 都没有，那不算是一个有效的 menuentry
        if [ $(echo "${menuentry_ctx}" | grep -c "vmlinuz-") -eq 0 ]
        then
            continue
        fi
        if [ $(echo "${menuentry_ctx}" | grep -c "initrd") -eq 0 ]
        then
            continue
        fi
        # 包含 rescue 字符串的，是救援模式用的，这里不适用
        if [ $(echo "${menuentry_ctx}" | grep -c "rescue") -ne 0 ]
        then
            continue
        fi

        menuentry=$(sed -n "${line}p" ${grub_path})
        initrd_file=$(echo "${menuentry_ctx}" | grep "initrd" | awk '{ print $2 }')
        initrd_file="/boot${initrd_file}"
        kernel_version=$(echo "${menuentry_ctx}" | grep "vmlinuz-" | awk '{ print $2 }' | awk -F "vmlinuz-" '{ print $2 }')

        if [ $(uname -r) != ${kernel_version} ]
        then
            continue
        fi

        if [ $(echo "${menuentry}" | grep -c "${saved_entry}") -eq 0 ]
        then
            continue
        fi
        echo "kernel_version: ${kernel_version}"
        echo "initrd_file: ${initrd_file}"
        echo "menuentry: ${menuentry}"
        echo "saved_entry: ${saved_entry}"
    done
}

get_menuentry_info
